package com.hmtech.ayp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.api.client.auth.openidconnect.IdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.hmtech.ayp.domain.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class GoogleTokenService {

    @Autowired
    private GoogleIdTokenVerifier googleIdTokenVerifier;

    public User parseIdToken(String idTokenStr) {
        if (StrUtil.isBlank(idTokenStr)) {
            throw new IllegalArgumentException("Invalid ID token");
        }
        try {
            GoogleIdToken idToken = googleIdTokenVerifier.verify(idTokenStr);
            IdToken.Payload payload = idToken.getPayload();
            String googleSub = payload.getSubject();
            User user = new User();
            user.setGoogleSub(googleSub);
            user.setNickname((String) payload.get("name"));
            user.setEmail((String) payload.get("email"));
            user.setAvatarUrl((String) payload.get("picture"));
            return user;
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid ID token");
        }
    }
}
